import utils from "../assets/utils/utils";
import {addUri, tellStatus, getGlobalStat, getActiveDownloads, pause} from '@/aria2/aria2.js';
import {aria2cPort} from "../config";

let _vm = {}
let activeDownloadTime = null
const path = `ws://localhost:${aria2cPort}/jsonrpc`
let that = null
export default {
	async init(vm) {
		that = this
		console.log("vm", vm)
		console.log("this", this)
		_vm = vm
		vm.socket = null
		if (typeof (WebSocket) === "undefined") {
			console.log("WebSocket未初始化")
		} else {
			console.log("init执行")
			// 实例化socket
			vm.socket = new WebSocket(path)
			// 监听socket连接
			vm.socket.onopen = this.open
			// 监听socket连接
			vm.socket.onclose = this.close
			// 监听socket错误信息
			vm.socket.onerror = this.error
			// 监听socket消息
			vm.socket.onmessage = this.getMessage
			
			await this.listenDownload(vm)
			activeDownloadTime = setInterval(async () => {
				await this.listenDownload(vm)
			}, 1000)
		}
	},
	open() {
		console.log("socket连接成功--", utils.getCurrentDateTime())
		_vm.socketReady = true
	},
	
	close() {
		_vm.socketReady = false
	},
	
	error() {
		_vm.socketReady = false
		_vm.socket = null
		console.log("连接错误--", utils.getCurrentDateTime())
	},
	async getMessage(msg) {
		console.log("收到消息", msg)
		console.log("msg.data", JSON.parse(msg.data))
		console.log("dateTime", utils.getCurrentDateTime())
		const msgData = JSON.parse(msg.data)
		const gid = msgData.params&&msgData.params[0].gid
		console.log("gid",gid)
		const file = await tellStatus(gid)
		console.log("file", file)
		//是否存在当前响应下载文件
		let currentDownFile = _vm.downloadFileList.find(v => (v.gid === gid))
		currentDownFile && that.updateCurrentDownFile(currentDownFile, file)
		// 修改状态
		// 当前下载文件
		switch (msgData.method) {
			case "aria2.onDownloadStart": //开始
				if (!currentDownFile) {
					_vm.downloadFileList.unshift({
						gid,
						method: msgData.method,
						status: '下载中',
						statusName: '下载中',
						fileName: '',
						speed: 0,
						size: 0,
						sizeCompleted: 0,//已完成大小
						progress: 0,//进度百分比
						remainingTime: 0,//还有多久下完
						dir: _vm.downloadPath,//文件保存路径
					})
				}
				break;
			case "aria2.onDownloadComplete":
				currentDownFile.status = '下载完成'
				currentDownFile.statusName = '下载完成'
				break;
			case "aria2.onDownloadPause":
				currentDownFile.status = '已暂停'
				currentDownFile.statusName = '已暂停'
				// window.$vm.taskNum = ++window.$vm.taskNum
				//下载错误
				break;
			case "aria2.onDownloadError":
				
				break;
		}
	},
	//监听下载情况
	async listenDownload(vm) {
		const res = await getActiveDownloads(vm)
		console.log("下载状态", res)
		res.forEach(file => {
			//当前下载文件
			const currentDownFile = vm.downloadFileList.find(v => (v.gid === file.gid))
			//如果存在修改
			if (currentDownFile) {
				console.log("currentDownFile", currentDownFile)
				this.updateCurrentDownFile(currentDownFile, file)
				// localStorage.setItem('downloadFileList', JSON.stringify(vm.downloadFileList))
				//不存在则添加
			} else {
			
			}
		})
	},
	// status: 下载任务的当前状态，例如 active, waiting, paused, error, complete, removed。
	// completedLength: 已下载的字节数。
	// totalLength: 文件的总字节数。
	// downloadSpeed: 当前下载速度（字节每秒）。
	// fileName:'',
	// speed:'',
	// size:'',
	// sizeCompleted:'',//已完成大小
	// progress:'',//进度百分比
	updateCurrentDownFile(currentDownFile, file) {
		const statusName = {
			'active': '下载中',
			'waiting': '等待中',
			'paused': '已暂停',
			'error': '下载失败',
			'complete': '下载完成',
			'removed': '下载移除',
		}
		currentDownFile.statusName = statusName[file.status]
		const filePathArr = file.files[0].path.split('/')
		currentDownFile.fileName = filePathArr[filePathArr.length - 1]
		currentDownFile.speed = utils.formatDownloadSpeed(file.downloadSpeed)
		// 计算下载进度
		const result = utils.calculateDownloadProgress(file.completedLength, file.totalLength, file.downloadSpeed);
		
		console.log(`已下载大小: ${result.downloadedSize}`); // 输出: 已下载大小: 5 MB
		console.log(`文件总大小: ${result.totalSize}`); // 输出: 文件总大小: 10 MB
		console.log(`下载进度: ${result.progress}`); // 输出: 下载进度: 50.00%
		currentDownFile.sizeCompleted = result.downloadedSize
		currentDownFile.size = result.totalSize
		currentDownFile.progress = result.progress
		currentDownFile.progressNum = result.progressNum
		currentDownFile.remainingTime = result.remainingTime
	},
	// 关闭
	closeWebSocket() {
		if (_vm.socket) {
			_vm.socket.close();
			clearInterval(activeDownloadTime)
		}
	}
}